package cn.ihna.test.jardemo.service;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author 京程(xianyingda)
 * @date 2020/11/22
 * @time 8:34 下午
 */
@Service
@Slf4j
public class CacheService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void addListCache(String cacheKey, Object payload, int max) {
        String cacheValueNode = JSON.toJSONString(payload);
        if (StringUtils.isAnyEmpty(cacheKey, cacheValueNode)) {
            return;
        }
        int size = getListSize(cacheKey);
        boolean needPop = false;
        if (max != -1 && size >= max) {
            needPop = true;
        }
        Long insert = redisTemplate.opsForList().leftPush(cacheKey, cacheValueNode);
        if (needPop && insert > 0) {
            redisTemplate.opsForList().rightPop(cacheKey);
        }
    }

    public void addListCache(String cacheKey, Object payload) {
        addListCache(cacheKey, payload, -1);
    }

    public int getListSize(String cacheKey) {
        return redisTemplate.opsForList().size(cacheKey).intValue();
    }

    /**
     * pageNumber   1
     * pageSize     10
     *
     * start    0   10
     * end      9   19
     *
     * @return
     */
    public <T> List<T> getListData(String cacheKey, int pageNumber, int pageSize, Class<T> clazz) {
        int start = pageSize * (pageNumber - 1);
        int end = start + pageSize - 1;
        List<String> stringData = redisTemplate.opsForList().range(cacheKey, start, end);
        List<T> res = new ArrayList<>();
        if (stringData != null) {
            stringData.stream().parallel().map(o -> JSON.parseObject(o, clazz)).forEachOrdered(res::add);
        }
        return res;
    }


}
